import { defineStore } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { TableRow } from '@/apis/analyze/type'
import { reCarbonLabel, reDeleteLabel, reEditLabel } from '@/apis/analyze'
export const analyzeStore = defineStore('analyze', {
  state: () => ({
    tableData: [] as TableRow[],
    editDialogVisible: false,
  }),
  actions: {
    async fetchAnalyze() {
      try {
        const result = await reCarbonLabel()
        console.log(result)
        this.tableData = result.data
        return result
      } catch (error) {
        ElMessage.error('数据获取失败！')
        console.error(error)
        return null
      }
    },
    async deleteRow(row: TableRow) {
      const result = await reDeleteLabel(row)
      if (result.code !== 200) {
        ElMessage.error('删除参数失败!')
      } else {
        this.tableData = this.tableData.filter((item) => item.id !== row.id)
        ElMessage({
          message: '删除成功.',
          type: 'success',
        })
      }
      return result
    },
    async saveEdit(formData: TableRow) {
      try {
        const result = await reEditLabel(formData)
        console.log(555)

        console.log(result)

        if (result.code === 200) {
          ElMessage({
            message: '编辑成功.',
            type: 'success',
          })
        } else {
          ElMessage.error('编辑失败！')
        }
        const index = this.tableData.findIndex(
          (item) => item.id === formData.id,
        )
        if (index !== -1) {
          this.tableData[index] = formData
        }
        this.editDialogVisible = false
        return result
      } catch (error) {
        ElMessage.error('编辑请求出错！')
        console.error(error)
        return null
      }
    },
    setEditDialogVisible(visible: boolean) {
      this.editDialogVisible = visible
    },
  },
})
